package com.xzzz.irda.guardcat.server.alert.listener;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.xzzz.common.base.util.MailUtil;
import com.xzzz.irda.guardcat.core.pojo.Alert;
import com.xzzz.irda.guardcat.server.setting.AlertSetting;
import lombok.extern.slf4j.Slf4j;

import javax.mail.Address;
import javax.mail.internet.InternetAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * 警告邮件监听类, 收到警告时, 会
 *
 * @author xzzz
 */
@Slf4j
public class AlertEmailListener {

    private static final String ALERT_MAIL_TITLE = "【重要】系统";
    private static final String SENDER = "491548320@qq.com";
    private static final String SENDER_PASSWORD = "Jasmine888";
    private static final String MAIL_HOST = "smtp.exmail.qq.com";
    private static final String MAIL_SMTP_PORT = "smtp.exmail.qq.com";

//    @AlertListener
    public void handle(Alert alert, AlertSetting alertSetting) {
        String[] emails = getEmail(alert, alertSetting);
        if (ArrayUtil.isEmpty(emails)) {
            return;
        }

        String prefix = alert.getLevel() == Alert.Level.INFO ? "通知" : "警告";

        String resultMessage = String.format(
            "<html><body>" +
            "<span style=\"color:red;font-size:17px;font-weight: bold;\">" + prefix + "标题:%s</span><br/><br/>" +
            prefix + "时间: %s<br/>" +
            prefix + "应用: %s<br/>" +
            prefix + "节点: %s<br/><br/>" +
            "追踪ID: %s<br/>" +
            prefix + "ID: %s<br/><br/>" +
            "<span style=\"font-size:17px;font-weight: bold;\">" + prefix + "内容:</span><br/>" +
            "<div style=\"border:1px solid #d9d9d9;padding:15px;border-radius:5px;margin-top:10px;\">%s</div>" +
            "<br/><br/><br/><br/><br/>" +
            "<div style=\"text-align:right;margin-right:20px;color:#a5a5a5;\">by 瞧瞧技术中台服务</div>" +
            "</body></html>",

            // ==================== 参数 ====================
            alert.getTitle(),
            DateUtil.format(alert.getCreTime(),"yyyy-MM-dd HH:mm:ss"),
            alert.getAppName(),
            alert.getHostName(),
            alert.getTraceId(),
            alert.getId(),
            alert.getContent()
        );

        for (String email : emails) {
            if (!email.contains("@")) {
                continue;
            }

            log.info("发布警告邮件: {}>{}", alert.getTitle(), email);

            try {
                if (StrUtil.isBlank(email) || !email.contains("@")) {
                    continue;
                }
                List<Address> list = new ArrayList<>();
                list.add(new InternetAddress(email));
                Address[] senderList = list.toArray(new Address[1]);
                MailUtil.sendMail(ALERT_MAIL_TITLE + prefix, resultMessage, SENDER, SENDER_PASSWORD, senderList, false, MAIL_HOST, MAIL_SMTP_PORT, true);
            } catch (Throwable e) {
                log.error("发送邮件失败,警告: {}, 配置: {}, 异常: {}", alert.toString(), email, e.getMessage());
            }
        }
    }

    private String[] getEmail(Alert alert, AlertSetting alertSetting) {
        String[] emails = new String[0];

        // 如果配置了警告渠道, 则使用
        if (alertSetting != null && StrUtil.isNotBlank(alertSetting.getEmail())) {
            emails = alertSetting.getEmail().split(",");
        }
        // 如果手动传入了警告渠道, 则优先使用手动传入的
        if (alert.getEmail() != null) {
            emails = alert.getEmail().split(",");
        }
        return emails;
    }
}
